import { useDevId } from '@ray-js/panel-sdk/lib/hooks/useDevId';
import { useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';

import { getCacheWeathers, init } from '@/api/getCacheWeather';
import { useProps } from '@ray-js/panel-sdk';
import { publishDps } from '@ray-js/ray';

export interface Weather {
  conditionNum: number;
  thigh: number;
  tlow: number;
  sunRiseTimeStamp: number;
  sunSetTimeStamp: number;
  [key: string]: any;
}

const mockData = [
  {
    windSpeed: '2.4',
    so2: 6,
    sunRise: '2025-10-11 05:54',
    pressure: 1009,
    sunRiseTimeStamp: 1760133240000,
    uvi: 5,
    pop: 0,
    tlow: 23,
    sunSet: '2025-10-11 17:29',
    no2: 11,
    pm25: 9,
    conditionNum: '120',
    windLevel: 1,
    condIconUrl: 'https://images.tuyacn.com/smart/weather/icon2/120.png',
    sunSetTimeStamp: 1760174940000,
    quality: '优',
    humidity: 76,
    pm10: 29,
    o3: 66,
    qualityLevel: 2,
    condition: '晴',
    realFeel: 35,
    qpf: 0,
    sunset: '2025-10-11 17:29',
    thigh: 35,
    windDir: 'NE',
    aqi: 29,
    co: 1,
    zoneId: 'Asia/Shanghai',
    temp: 30,
    sunrise: '2025-10-11 05:54',
  },
];

const decodeTime = (str: string) => {
  if (str.length !== 8) {
    return {
      sunRiseTime: '',
      sunSetTime: '',
    };
  }

  const sunRiseTime = parseInt(str.slice(0, 4), 16) * 60 * 1000;
  const sunSetTime = parseInt(str.slice(4, 8), 16) * 60 * 1000;

  const baseTime =
    dayjs()
      .startOf('day')
      .unix() * 1000;

  return {
    sunRiseTime: baseTime + sunRiseTime,
    sunSetTime: baseTime + sunSetTime,
  };
};

const encodeTime = (time: number) => {
  const dayTime = dayjs(time);

  const minute = dayTime.hour() * 60 + dayTime.minute();

  return `${minute.toString(16).padStart(4, '0')}`;
};

export const useWeekWeather = () => {
  const { deviceId } = useDevId();

  const { sunrise_sunset_time: sunriseSunsetTime } = useProps();

  const [weekWeathers, setWeekWeathers] = useState<Weather[]>([]);
  const [loading, setLoading] = useState(true);

  // @ts-ignore
  useEffect(async () => {
    setLoading(true);
    const cacheWeathers = getCacheWeathers();
    if (cacheWeathers?.weathers?.length) {
      setLoading(false);
      setWeekWeathers((cacheWeathers.weathers as unknown) as Weather[]);
      return;
    }

    const nextWeathers = await init();

    setLoading(false);

    setWeekWeathers((nextWeathers?.weathers as unknown) as Weather[]);
  }, []);

  useEffect(() => {
    if (weekWeathers?.length) {
      const startTime = encodeTime(weekWeathers[0].sunRiseTimeStamp);

      const endTime = encodeTime(weekWeathers[0].sunSetTimeStamp);

      if (sunriseSunsetTime !== `${startTime}${endTime}`) {
        publishDps({
          sunrise_sunset_time: `${startTime}${endTime}`,
        });
      }
    }
  }, [weekWeathers, sunriseSunsetTime]);

  const weekNumber = dayjs().format('d');

  return {
    weekWeathers: weekWeathers?.length === 1 ? weekWeathers[0] : mockData[0],
    loading,
    weekNumber,
  };
};
